/**
 * Created by linxin on 2017/3/11.
 */
// import {
//   asyncRoutes,
//   constantRoutes
// } from '@/router'
import {
  hasPermission,
  filterAsyncRoutes
} from '../../utils/auth';

function findRoute(routes, fullPath) {
  for (let i in routes) {
    let r = routes[i];
    let path = r.fullPath || r.path
    if (path === fullPath) {
      return r
    }
    if (r.children) {
      r = findRoute(r.children, fullPath)
      if (r) return r
    }
  }
  return null
}

function getRouteChildren(routes, fullPath) {
  let r = findRoute(routes, fullPath) || {};
  return r.children || [];
}

export default {
  setRoutes: ({
    commit
  }, param) => commit('SETROUTES', {
    routes: param
  }),
  setAddRoutes: ({
    commit
  }, param) => commit('SETADDROUTES', {
    addRoutes: param
  }),
  setSubPages: ({
    commit
  }, subPages) => commit('SET_SUBPAGES', subPages),
  generateRoutes({
    commit
  }, roles) {
    return new Promise(resolve => {
      let accessedRoutes
      let roleNames = roles.map(e => e.name || e)
      if (roleNames.includes('developer')) {
        accessedRoutes = asyncRoutes || []
      } else {
        accessedRoutes = filterAsyncRoutes(asyncRoutes, roles)
      }
      commit('SET_ROUTES', accessedRoutes)
      resolve(accessedRoutes)
    })
  },

  generateSidebarRoutes({
    commit
  }, fullPath) {
    return new Promise(resolve => {
      let subPages = getRouteChildren(constantRoutes, fullPath) || []

      if (subPages.length == 0) {
        subPages = getRouteChildren(asyncRoutes, fullPath)
      }

      commit('SET_SUBPAGES', subPages)

      resolve(subPages)
    })
  }
}
